package com.cyrus.rabbitmq.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Author: Cyrus
 * @CreateDate: 2020/12/1
 */
@Configuration
public class RabbitMQConfig {
    //public static final String EXCHANGE_NAME = "boot_topics_exchange";
    public static final String EXCHANGE_NAME = "boot_exchange_ttl";
    //public static final String QUEUE_NAME = "boot_queue";
    //public static final String QUEUE_NAME = "boot_confirm";
    // public static final String QUEUE_NAME = "boot_Qos";
    public static final String QUEUE_NAME = "boot_queue_ttl";
    public static final String ROUTING_KEY = "boot.#";

    public static final String DEAD_EXCHANGE_NAME = "dead_boot_exchange_ttl";
    public static final String DEAD_QUEUE_NAME = "dead_boot_queue_ttl";

    //1、交换机
    @Bean("bootExchange")
    public Exchange bootExchange() {
        return ExchangeBuilder.topicExchange(EXCHANGE_NAME).durable(true).build();
    }

    //2、队列
    @Bean("bootQueue")
    public Queue bootQueue() {
        //.ttl(10000) 设置所有队列消息10秒后过期
        /**
         * public QueueBuilder ttl(int ttl) {
         * 		return withArgument("x-message-ttl", ttl);
         *        }
         * 封装了"x-message-ttl"为key,手动设置过期时间value
         */
        //return QueueBuilder.durable(QUEUE_NAME).ttl(100000).build();
        return QueueBuilder.durable(QUEUE_NAME)
                .deadLetterExchange(DEAD_EXCHANGE_NAME) //绑定死信交换机的名称
                .deadLetterRoutingKey("dead_boot.Hello")
                .ttl(20000)  //设置队列过期事件 ，过期后进入死信队列
                .maxLength(10)  //设置队列最大容量，超过后进入死信队列
                .build();
    }


    //死信交换机
    @Bean("deadExchange")
    public Exchange deadExchange() {
        return ExchangeBuilder.topicExchange(DEAD_EXCHANGE_NAME).durable(true).build();
    }

    //2、队列
    @Bean("deadQueue")
    public Queue deadQueue() {
        return QueueBuilder.durable(DEAD_QUEUE_NAME).build();
    }



    /**
     * 1、知道那个队列
     * 2、知道那个交换机
     * 3、routing key
     */
    @Bean
    public Binding bindQueueExchange(@Qualifier("bootQueue") Queue queue, @Qualifier("bootExchange") Exchange exchange) {
        //绑定交换机与队列
        return BindingBuilder.bind(queue).to(exchange).with(ROUTING_KEY).noargs();
    }

    /**
     * 绑定死信交换机
     */
    @Bean
    public Binding bindDeadQueueExchange(@Qualifier("deadQueue") Queue queue, @Qualifier("deadExchange") Exchange exchange) {
        //绑定死信交换机与队列
        return BindingBuilder.bind(queue).to(exchange).with("dead_boot.#").noargs();
    }
}
